<?PHP
/**
 * $Rev: 13 $
 * $Id: dispatcher.php 13 2013-03-18 16:00:24Z vad.oparin@gmail.com $
 */
class dispatcher extends object {
    protected $parent;
    protected $innerRoute;
    protected $parameters;

    public function __construct($parent) {
        $this->parent = $parent;
    }

    public function init() {
        $routeFormat = $this->parent->getRouteFormat();
        $this->addBehavior($routeFormat, array('parent' => $this, ));
        return $this;
    }

    protected function setInnerRoute() {
        $innerRoute = $this->getRoute();
        $this->innerRoute['module'] = $innerRoute['module'];
        $this->innerRoute['controller'] = $innerRoute['controller'];
        $this->innerRoute['action'] = $innerRoute['action'];
        $this->parameters = $innerRoute['parameters'];
    }

    public function delegate() {
        $this->setInnerRoute();
        if ($this->parent->registerModule($this->innerRoute['module'])) {
            $controllerName = $this->innerRoute['controller'] . 'Controller';
            $actionName = $this->innerRoute['action'] . 'Action';
            if ((class_exists($controllerName)) && (is_callable(array(
                $controllerName,
                $actionName,
            )))) {
                $controller = new $controllerName;
                $this->parent->controller = $controller;
                call_user_func_array(array(
                    $controller,
                    $actionName,
                ), $this->parameters);
            } else {
                $this->redirect404();
            }
        }

    }

    public function redirect($url, $status = 302, $exit = true) {
        header('Location: ' . $url, true, $status);
    }

    public function redirect404() {
        $url = $this->createAbsoluteUrl(array('action' => 'error404', ));
    }

}
